import styles from '@/common/form.less';
import PateoAuthButtons from '@/common/PateoAuthButtons/PateoAuthButtons';
import DescriptionList from '@/components/DescriptionList/index';
import IPDADetailModal from '@/components/ipda/ipdaDetailModal';
import SIMDetailModal from '@/components/simCard/simCardDetailModal';
import TboxDetailModal from '@/components/Tbox/tboxDetailModel';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import { getDicByKey } from '@/support/common';
import { Button, Card, Col, Form, Input, message, Row, Table } from 'antd';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Ellipsis from '../../../components/Ellipsis';
import VehicleBindingModel from '../baseUserBind/vehicleBindingModel';
import VehicleDetailModal from './vinDetailModal';

const { Description } = DescriptionList;
const FormItem = Form.Item;
@connect(state => ({
  baseUser: state.baseUser,
}))
// @Form.create()
export default class BasicProfile extends Component {
  static contextTypes = {
    authButton: PropTypes.array,
    dicData: PropTypes.any,
  };
  formRef = React.createRef();
  VehicleBindingRef = React.createRef();
  state = {
    visible: false,
    baseUserDetailData: {},
    vehicleDetailData: [],
    userAccountSid: '',
    tboxDetailVisible: false,
    simDetailVisible: false,
    ipdaDetailVisible: false,
    vinDetailVisible: false,
    vinDetailModelData: {},
    tboxDetailModelData: {},
    simDetailModelData: {},
    ipdaDetailModelData: {},
  };
  componentWillMount() {}
  componentDidMount() {}
  handleBindingDate = () => {
    this.VehicleBindingRef.showModel(this.state.userAccountSid);
  };
  handleSearch = fieldsValue => {
    if (fieldsValue.mobilePhone === undefined && fieldsValue.idNo === undefined) {
      message.error('请输入手机号或证件号');
      return;
    }
    this.props.dispatch({
      type: 'baseUser/findProfile',
      payload: fieldsValue,
      callback: response => {
        if (response.code === '200' || response.code === '0') {
          this.setState({
            baseUserDetailData: response.userProfile,
            vehicleDetailData: response.carList ? response.carList : '',
            visible: true,
          });
        } else {
          this.setState({
            visible: false,
            baseUserDetailData: {},
            vehicleDetailData: {},
          });
          message.error(response.statusMessage || response.description);
        }
      },
    });
  };
  handleFormReset = () => {
    this.formRef.current.resetFields();
    this.setState({
      visible: false,
      baseUserDetailData: {},
      vehicleDetailData: {},
    });
  };
  handleDetailVIN = vin => {
    const { dispatch } = this.props;
    dispatch({
      type: 'basedata/findVehicleProfile',
      payload: vin,
      callback: response => {
        if (response.statusCode === '0') {
          if (response.data) {
            this.setState({ vinDetailModelData: response.data, vinDetailVisible: true });
          }
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };
  handleDetailTbox = deviceId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'tbox/fetchtboxdetail',
      payload: deviceId,
      callback: tboxDetail => {
        this.setState({ tboxDetailModelData: tboxDetail.data, tboxDetailVisible: true });
      },
    });
  };
  handleDetailSIM = deviceId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'simCard/findById',
      payload: deviceId,
      callback: simDetail => {
        if (simDetail.statusCode === '0') {
          this.setState({ simDetailModelData: simDetail.data, simDetailVisible: true });
        } else {
          message.error(simDetail.statusMessage);
        }
      },
    });
  };
  handleDetailIPDA = deviceId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ipda/findById',
      payload: deviceId,
      callback: ipdaDetail => {
        if (ipdaDetail.statusCode === '0') {
          this.setState({ ipdaDetailModelData: ipdaDetail.data, ipdaDetailVisible: true });
        } else {
          message.error(ipdaDetail.status.description);
        }
      },
    });
  };
  unbind = accountBindSid => {
    const { dispatch } = this.props;
    dispatch({
      type: 'baseUser/unbind',
      payload: { accountBindSid },
      callback: data => {
        if (data.code === '200') {
          message.success('解绑成功');
        } else {
          message.error(data.statusMessage, 3);
        }
      },
    }).then(() => {
      dispatch({
        type: 'baseUser/fetchVehicleByUserAccountSid',
        payload: this.state.userAccountSid,
        callback: data => {
          this.setState({ vehicleDetailData: data });
        },
      });
    });
  };

  resetSecurityCode = record => {
    const { ipda, tbox, vin } = record;
    const { dispatch } = this.props;
    dispatch({
      type: 'baseUser/resetSecurityCode',
      payload: { vin, tbox, ipda },
      callback: data => {
        if (data.statusCode === '0') {
          message.success('安全码重置成功！', 2);
        } else {
          message.error(data.statusMessage);
        }
      },
    });
  };

  renderForm() {
    // const { getFieldDecorator } = this.props.form;
    return (
      <Form ref={this.formRef} onFinish={this.handleSearch} layout="inline">
        <Row>
          <Col md={9} sm={24}>
            <FormItem label="手机号" name="mobilePhone">
              <Input placeholder="请输入手机号" maxLength={11} />
            </FormItem>
          </Col>
          <Col md={9} sm={24} offset={1}>
            <FormItem label="证件号" name="idNo">
              <Input placeholder="请输入证件号" />
            </FormItem>
          </Col>
          <Col md={4} sm={24} offset={1}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }
  render() {
    const isAuth = true; // this.context.authButton.includes('baseUser-opt');
    const tboxAuth = true; // this.context.authButton.includes('tbox');
    const ipdaAuth = true; // this.context.authButton.includes('ipda');
    const simCardAuth = true; // this.context.authButton.includes('simCard');
    const { baseUserDetailData } = this.state;
    const status = ['', '已销售', '车厂', '销售取消', '经销商'];
    const type = ['非车主', '车主'];
    const columns = [
      {
        title: 'VIN号',
        dataIndex: 'vin',
        render: text => {
          return <a onClick={() => this.handleDetailVIN(text)}>{text}</a>;
        },
      },
      {
        title: '品牌',
        dataIndex: 'brandId',
        render: val => getDicByKey(this.context.dicData, 'optBrand', val),
      },
      {
        title: '车系',
        dataIndex: 'seriesId',
        render: val => getDicByKey(this.context.dicData, 'vehicleSeries', val),
      },
      {
        title: '车型',
        dataIndex: 'styleId',
        render: val => getDicByKey(this.context.dicData, 'vehicleType', val),
      },
      {
        title: '车辆状态',
        dataIndex: 'status',
        render: val => status[val],
      },
      {
        title: 'SIM卡',
        dataIndex: 'sim',
        render: text => {
          return simCardAuth ? <a onClick={() => this.handleDetailSIM(text)}>{text}</a> : text;
        },
      },
      {
        title: 'T-BOX',
        dataIndex: 'tbox',
        render: text => {
          return tboxAuth ? <a onClick={() => this.handleDetailTbox(text)}>{text}</a> : text;
        },
      },
      {
        title: 'IPDA',
        dataIndex: 'ipda',
        render: text => {
          return ipdaAuth ? <a onClick={() => this.handleDetailIPDA(text)}>{text}</a> : text;
        },
      },
      {
        title: '与用户关系',
        dataIndex: 'relationshipType',
        render: val => type[val],
        // }, {
        //   title: '操作',
        //   dataIndex: '操作',
        //   width: 100,
        //   fixed: 'right',
        //   render: (text, record) => {
        //     return <Popconfirm title="确定要解绑该车辆吗?" onConfirm={() => this.unbind.bind(this)(record.accountBindSid)}>{isAuth ? <a>解绑</a> : ''}</Popconfirm>;
        //   },
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: '15%',
        render: (text, record) => {
          const btns = [];
          //重置安全码
          if (type[record.relationshipType] === '车主') {
            btns.push({
              title: '重置安全码',
              key: 'delete',
              message: '是否确认重置安全码？',
              Popconfirm: true,
              onConfirm: () => this.resetSecurityCode.bind(this)(record),
            });
          }

          return <PateoAuthButtons authStr="baseUserProfile-opt" btns={btns} />;
        },
      },
    ];
    return (
      <PageHeaderLayout>
        <div className={styles.tableListForm}>{this.renderForm()}</div>
        {this.state.visible ? (
          <div>
            <br />
            <Card bordered={false} type="inner" title="用户信息">
              <DescriptionList>
                <Description term="用&nbsp;&nbsp;户&nbsp;&nbsp;名" style={{ width: '50%' }}>
                  <Ellipsis length={10} tooltip>
                    {baseUserDetailData.userName}
                  </Ellipsis>
                </Description>
                <Description term="性&nbsp;&nbsp;&nbsp;&nbsp;别" style={{ width: '50%' }}>
                  {getDicByKey(this.context.dicData, `sex`, baseUserDetailData.sexuality + '')}
                </Description>
                <Description term="证件类型" style={{ width: '50%' }}>
                  {getDicByKey(this.context.dicData, `certType`, baseUserDetailData.idType + '')}
                </Description>
                <Description term="证件号" style={{ width: '50%' }}>
                  <Ellipsis length={18} tooltip>
                    {baseUserDetailData.idNo}
                  </Ellipsis>
                </Description>
                <Description term="手&nbsp;&nbsp;机&nbsp;&nbsp;号" style={{ width: '50%' }}>
                  {baseUserDetailData.mobilePhone}
                </Description>
                <Description term="邮&nbsp;&nbsp;&nbsp;&nbsp;箱" style={{ width: '50%' }}>
                  {baseUserDetailData.email}
                </Description>
                <Description term="紧急联系人" style={{ width: '50%' }}>
                  {baseUserDetailData.contract}
                </Description>
                <Description term="紧急联系人电话" style={{ width: '50%' }}>
                  {baseUserDetailData.contractPhone}
                </Description>
              </DescriptionList>
            </Card>
            {/*<div>*/}
            {/*{ isAuth ? <Button icon="plus" type="primary" onClick={this.handleBindingDate}>绑定车辆</Button> : '' }*/}
            {/*</div>*/}
            <br />
            <Card bordered={false} type="inner" title="车辆信息">
              {this.state.vehicleDetailData ? (
                <Table
                  rowKey={record => record.vin}
                  // loading={loading}
                  dataSource={this.state.vehicleDetailData}
                  columns={columns}
                  pagination={false}
                  scroll={{ x: 1300 }}
                />
              ) : (
                <h3>该用户无绑定车辆</h3>
              )}
            </Card>
          </div>
        ) : null}
        <VehicleDetailModal
          changeVisible={() => this.setState({ vinDetailVisible: false, vinDetailModelData: {} })}
          visible={this.state.vinDetailVisible}
          detailModelData={this.state.vinDetailModelData}
          dispatch={this.props.dispatch}
        />
        <TboxDetailModal
          changeVisible={() => this.setState({ tboxDetailVisible: false, tboxDetailModelData: {} })}
          visible={this.state.tboxDetailVisible}
          detailModelData={this.state.tboxDetailModelData}
          dispatch={this.props.dispatch}
        />
        <SIMDetailModal
          changeVisible={() => this.setState({ simDetailVisible: false, simDetailModelData: {} })}
          visible={this.state.simDetailVisible}
          detailModelData={this.state.simDetailModelData}
          dispatch={this.props.dispatch}
        />
        <IPDADetailModal
          changeVisible={() => this.setState({ ipdaDetailVisible: false, ipdaDetailModelData: {} })}
          visible={this.state.ipdaDetailVisible}
          detailModelData={this.state.ipdaDetailModelData}
          dispatch={this.props.dispatch}
        />
        <VehicleBindingModel
          ref={this.VehicleBindingRef}
          icon="plus"
          type="primary"
          dispatch={this.props.dispatch}
          userAccountSid={this.state.userAccountSid}
          setVehicle={data => this.setState({ vehicleDetailData: data })}
        />
      </PageHeaderLayout>
    );
  }
}
